package view;

import java.awt.Toolkit;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Shell;

import view.resources.Images;
import control.Storage;
import control.Util;

public class MemoryCard {

	private boolean bActive = false;
	private final Button button;
	private final int iNumber;
	private int iImageNumber;
	private Image image;

	public MemoryCard(Shell shell, int number) {
		iNumber = number;

		getImage();

		button = new Button(shell, SWT.PUSH);
		button.setImage(Images.DEFAULT.createImage());
		button.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				if (!Storage.getInstance().isTurnPause()) {
					if (bActive) {
						Toolkit.getDefaultToolkit().beep();
					} else {

						bActive = true;
						button.setImage(image);
						button.update();

						try {
							Thread.sleep(300);
							Storage.getInstance().addCard(MemoryCard.this);
						} catch (InterruptedException e1) {
						}

					}

					Util.checkCards();
				}
			}

		});

	}

	public Button getButton() {
		return button;
	}

	private void getImage() {

		iImageNumber = Util.getRandomNumber(1, 25);

		if (Storage.getInstance().getImageMap().containsKey(iImageNumber)
				&& Storage.getInstance().getCardMap().get(iImageNumber) < 2) {
			int iCardCount = Storage.getInstance().getCardMap()
					.get(iImageNumber);
			image = Storage.getInstance().getImageMap().get(iImageNumber);
			Storage.getInstance().getCardMap()
					.put(iImageNumber, (iCardCount + 1));

		} else {
			getImage();
		}

	}

	public int getImageNumber() {
		return iImageNumber;
	}

	public int getNumber() {
		return iNumber;
	}

	public void setbActive(boolean bActive) {
		this.bActive = bActive;
	}

}
